from flask import Flask, render_template, url_for, request
import json
from db import conn
app = Flask(__name__)
from unidiff import PatchSet
from io import StringIO

repos = list()
with open("data/repos","r") as fp:
    
    for line in fp:
        repo = {}
        item = [item.strip() for item in line.split(" ")]
        repo["id"], repo["repo_name"],repo["user_name"] = item
        repos.append(repo)

@app.route('/')
def index():
    return render_template("index.html",repos = repos)

def parsFile(repo_id, pr_n):
    cursor = conn.cursor()
    cursor.execute("select diff from pr_diff where project_id =%s and pr_id=%s",(repo_id, pr_n))
    result = cursor.fetchone()
    cursor.close()
    if result == None:
        return ""
    changed_files = []
    ps = PatchSet(StringIO(result[0]))
    for d in ps:
		if d.source_file == "/dev/null":
			changed_files.append(d.target_file[1:-1])
		else:
			changed_files.append(d.source_file[1:-1])
    return ";\n".join(changed_files)

def detectDupPR(repo_id, pr_n):
    prs = []
    cursor = conn.cursor()
    cursor.execute('select author_name,created_at,title,description, pr_number from prs where prj_id=%s and pr_number>%s limit 5',(repo_id,pr_n))  
    results = cursor.fetchall()
    cursor.close()
    for result in results:
        pr = {}
        pr["pr_author"],pr["pr_time"],pr["pr_title"],pr["pr_desc"] = result[0:-1]
        pr["pr_number"] = result[-1]
        pr["pr_file"] = parsFile(repo_id,result[-1])
        prs.append(pr)
    
    return prs

@app.route('/detect')
def detect():
    repo_id, pr_n = request.args.get("repo_id"), request.args.get("pr_n")
    cursor = conn.cursor()
    cursor.execute('select author_name,created_at,title,description from prs where prj_id=%s and pr_number=%s',(repo_id,pr_n))  
    result = cursor.fetchone()
    cursor.close()
    if result is None:
       return  json.dumps({"success":"false"},ensure_ascii=False)  
    else:

        pr = {}
        pr["pr_author"],pr["pr_time"],pr["pr_title"],pr["pr_desc"] = result
        pr["pr_number"] = pr_n
        pr["pr_file"] = parsFile(repo_id,pr_n)

        dupPRs = detectDupPR(repo_id, pr_n)

        return json.dumps({"success":"true", "exa_pr":pr, "prs":dupPRs},ensure_ascii=False)  

        